import os
import subprocess
import logging

# Configure logging
logging.basicConfig(filename='publish_to_ostree_repo.log', level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

def log_message(message):
    """Log a message to both console and log file."""
    print(message)
    logging.info(message)

def run_command(command):
    """Run a shell command and handle errors."""
    try:
        result = subprocess.run(command, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stdout.decode('utf-8')
        log_message(output)
    except subprocess.CalledProcessError as e:
        error_message = f"Error executing command: {e.cmd}\n{e.stderr.decode('utf-8')}"
        log_message(error_message)
        exit(1)

def commit_to_repo(repo_path, branch_name, commit_message, source_dir):
    """Commit files to the OSTree repository."""
    run_command(f"ostree --repo={repo_path} commit -b {branch_name} -s \"{commit_message}\" --tree=dir={source_dir}")

def update_repo_summary(repo_path):
    """Update the summary file for the OSTree repository."""
    run_command(f"ostree summary -u --repo={repo_path}")
def main():
    repo_path = "/srv/ostree/repo"
    branch_name = "testbranch"
    commit_message = "New commit"
    source_dir = "/home/user/source_files"
    
    # Commit files to the OSTree repository
    log_message(f"Committing files from '{source_dir}' to branch '{branch_name}' in OSTree repository at '{repo_path}'...")
    commit_to_repo(repo_path, branch_name, commit_message, source_dir)
    
    # Update the repository summary
    log_message("Updating OSTree repository summary...")
    update_repo_summary(repo_path)
    
    log_message("OSTree repository update complete.")
if __name__ == "__main__":
    main()

